package org.jeecg.modules.demo.wz.utils;

import com.alibaba.fastjson.JSONObject;
import org.jeecg.modules.demo.wz.entity.WeatherDTO;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;

import java.io.IOException;

/**
 * Created by mt on 2020-08-21
 */
public class WeatherUtils {

    private static OkHttpClient httpClient = new OkHttpClient();

    /**
     * 通过城市名称获取该城市的天气信息
     * @param cityName
     * @return
     */
    public static String GetWeatherDate(String cityName) {
        String weather_url = "http://wthrcdn.etouch.cn/weather_mini?city=" + cityName;
        return httpGet(weather_url);
    }

    /**
     * okhttp get请求
     * @param url
     * @return
     */
    private static String httpGet(String url){
        String body = null;
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = httpClient.newCall(request);
        try {
            body = call.execute().body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;
    }

    /**
     * 将json格式数据进行解析，返回一个WeatherDTO对象
     * @param weatherInfoByJson
     * @return
     */
    public static WeatherDTO getWeather(String weatherInfoByJson){
        System.out.println(weatherInfoByJson);

        return JSONObject.parseObject(weatherInfoByJson, WeatherDTO.class);
    }

    public static void main(String[] args) {
        String info = WeatherUtils.GetWeatherDate("南阳");
        WeatherDTO weather = getWeather(info);
        System.out.println(weather.toString());
    }
}